package com.weilele.library.banner.impl.ybanner

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.weilele.mvvm.R
import com.weilele.mvvm.base.helper.SingleClickListener
import com.weilele.mvvm.utils.activity.inflate
import com.weilele.library.banner.YzsBanner
import com.weilele.library.banner.impl.ybanner.transformer.ScaleInTransformer
import com.weilele.mvvm.utils.safeGet
import java.lang.ref.WeakReference

internal class YzsYbannerImpl<T : YzsBanner.BannerData>(viewGroup: ViewGroup) :
    YzsBanner<T> {
    companion object {
        //最大的banner数字，实现假的无线轮播
        private const val MAX_COUNT = Int.MAX_VALUE - 10
    }

    private val defaultListener = YzsBanner.DefaultListener<T>()

    //监听器
    private var listener: YzsBanner.Listener<T>? = null
        get() {
            return field ?: defaultListener
        }

    //viewpager2
    private val ybanner = viewGroup.inflate(R.layout.library_item_ybanner, false) as YBanner

    //recyclerView
    private val rcv = ybanner.rcv

    //页面之间的间距
    private var adapterItemViewMargin = 0

    //时候只允许当前页面相应点击
    private var onlyClickCurrentItem = true

    init {
        if (ybanner.parent == null) {
            viewGroup.addView(ybanner)
        }
        initViewPager2(viewPager2)
        viewGroup.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View?) {
                if (ybanner.parent == null && v is ViewGroup) {
                    v.addView(ybanner)
                }
            }

            override fun onViewDetachedFromWindow(v: View?) {
                if (v is ViewGroup) {
                    v.removeView(ybanner)
                }
            }
        })
    }

    override fun setListener(listener: YzsBanner.Listener<T>) {
        this.listener = listener
    }

    override fun setDatas(datas: MutableList<T>, layoutId: Int?, isCanInfiniteScroll: Boolean) {
        if (!isCanInfiniteScroll) {
            //不能无限滚动，关闭自动滚动
            stopAutoScroll()
            setCanAutoScroll(false)
        }
        val oldAdapter = viewPager2.adapter.safeGet<PagerAdapter>()
        if (oldAdapter?.dates == datas && oldAdapter.layoutId == layoutId) {
            oldAdapter.isCanInfiniteScroll = isCanInfiniteScroll
            oldAdapter.notifyDataSetChanged()
        } else {
            viewPager2.adapter = PagerAdapter(datas, layoutId, isCanInfiniteScroll)
        }
    }

    override fun getDatas(): MutableList<T>? {
        return viewPager2.adapter.safeGet<PagerAdapter>()?.dates
    }

    private fun initViewPager2(vp2: ViewPager2) {
        vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                viewPager2.adapter.safeGet<YzsYbannerImpl<T>.PagerAdapter>()?.apply {
                    val index = position % datasCount
                    listener?.onBannerSelected(dates[index], index)
                }
            }
        })
        //设置默认的
        setPageTransformer(ScaleInTransformer())
    }

    override fun setPageTransformer(transformer: ViewPager2.PageTransformer?) {
        viewPager2.setPageTransformer(transformer)
    }

    override fun canOnlyClickCurrentItem(onlyClick: Boolean) {
        onlyClickCurrentItem = onlyClick
    }

    override fun setLifecycle(lifecycleOwner: LifecycleOwner?) {
        ybanner.setLifecycle(lifecycleOwner)
    }

    override val viewPager2: ViewPager2
        get() = ybanner.viewPager2


    override fun setItemMargin(margin: Int) {
        adapterItemViewMargin = margin
    }

    override fun setPagerMargin(margin: Int) {
        if (isVertical()) {
            rcv.setPadding(0, margin, 0, margin)
        } else {
            rcv.setPadding(margin, 0, margin, 0)
        }
        rcv.clipToPadding = false
    }

    override fun setCanAutoScroll(enable: Boolean) {
        ybanner.canAutoScroll = enable
    }

    override fun setAutoScrollDuration(duration: Int) {
        ybanner.autoScrollDuration = duration
    }

    override fun setAutoScrollInterval(time: Long) {
        ybanner.autoScrollInterval = time
    }

    override fun startAutoScroll() {
        ybanner.start()
    }

    override fun stopAutoScroll() {
        ybanner.stop()
    }

    private fun isVertical(): Boolean {
        return viewPager2.orientation == ViewPager2.ORIENTATION_VERTICAL
    }

    private inner class PagerAdapter(
        val dates: MutableList<T>,
        val layoutId: Int?,
        var isCanInfiniteScroll: Boolean
    ) : RecyclerView.Adapter<PagerHolder>() {
        val datasCount = dates.count()

        init {
            if (isCanInfiniteScroll) {
                val currentIndex = MAX_COUNT / 2
                val index = currentIndex % datasCount
                rcv.scrollToPosition(currentIndex - index)
            }
        }

        override fun onBindViewHolder(holder: PagerHolder, position: Int) {
            val index = position % datasCount
            listener?.onLoadBanner(holder.itemView, dates[index], index)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagerHolder {
            val view = if (layoutId != null) {
                LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
            } else {
                ImageView(parent.context).apply {
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    scaleType = ImageView.ScaleType.FIT_XY
                }
            }
            return PagerHolder(this, view.apply {
                layoutParams = RecyclerView.LayoutParams(
                    RecyclerView.LayoutParams.MATCH_PARENT,
                    RecyclerView.LayoutParams.MATCH_PARENT
                ).apply {
                    if (isVertical()) {
                        topMargin = adapterItemViewMargin
                        bottomMargin = adapterItemViewMargin
                    } else {
                        marginStart = adapterItemViewMargin
                        marginEnd = adapterItemViewMargin
                    }

                }
            })
        }

        override fun getItemCount(): Int = if (isCanInfiniteScroll) MAX_COUNT else dates.count()
    }

    private inner class PagerHolder(adapter: PagerAdapter, itemView: View) :
        RecyclerView.ViewHolder(itemView) {
        init {
            itemView.setOnClickListener(SingleClickListener {
                val index = bindingAdapterPosition % adapter.datasCount
                viewPager2.apply {
                    if (onlyClickCurrentItem) {
                        if (currentItem == bindingAdapterPosition) {
                            listener?.onBannerClick(itemView, adapter.dates[index], index)
                        }
                    } else {
                        listener?.onBannerClick(itemView, adapter.dates[index], index)
                    }
                }
            })
        }
    }
}